﻿using System.Data;
using NPOI.SS.UserModel;

namespace DocumentMaking.Lib.Services;

public static class ExcelService
{
    public static DataTable GetExcelList(Stream stream)
    {
        var table = new DataTable();
        var workbook = WorkbookFactory.Create(stream);
        var sheet = workbook.GetSheetAt(0);

        var rowsCount = sheet.PhysicalNumberOfRows;
        var colsCount = sheet.GetRow(0).PhysicalNumberOfCells;
        for (var i = 0; i < colsCount; i++)
            table.Columns.Add(sheet.GetRow(0).GetCell(i).ToString());
        for (var x = 0; x < rowsCount; x++)
        {
            if (x == 0) continue;
            var dr = table.NewRow();
            for (var y = 0; y < colsCount; y++)
                dr[y] = sheet.GetRow(x).GetCell(y).ToString();
            table.Rows.Add(dr);
        }

        return table;
    }

    public static List<T> DataTableToList<T>(DataTable dt) where T : new()
    {
        try
        {
            if (dt == null! || dt.Rows.Count == 0) return [];
            var toList = new List<T>();
            var columns = dt.Columns;
            foreach (DataRow dr in dt.Rows)
            {
                var t = new T();
                var properties = t.GetType().GetProperties();
                foreach (var p in properties)
                {
                    var name = p.Name;
                    if (!columns.Contains(name)) continue;
                    if (!p.CanWrite) continue;

                    var value = dr[name];

                    if (value != DBNull.Value)
                        p.SetValue(t, value, null);
                }

                toList.Add(t);
            }

            return toList;
        }
        catch
        {
            return [];
        }
    }
}